﻿using OA.Common;
using OA.Models;
using System;
using System.IO;
using System.Web.Mvc;

namespace OA.Controllers.Common
{
    public class FileController : Controller
    {
        const string FILE_PATH = @"\Files\CloudStorage";

        /// <summary>
        ///  plupload 文件上传
        /// </summary>
        /// <param name="chunk"></param>
        /// <param name="name">唯一名</param>
        /// <param name="pathload">文件路径</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult Uploader(int? chunk, string name, string pathload)
        {
            var path = Server.MapPath(FILE_PATH + pathload);
            var files = Request.Files[0];
            chunk = chunk ?? 0;

            try
            {
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                using (var fs = new FileStream(Path.Combine(path, name), chunk == 0 ? FileMode.Create : FileMode.Append))
                {
                    var buffer = new byte[files.InputStream.Length];
                    files.InputStream.Read(buffer, 0, buffer.Length);
                    fs.Write(buffer, 0, buffer.Length);
                }

                // 文件名
                // 后缀名
                // 文件路径
                var result = new Models.File()
                {
                    Name = name,
                    Extension = FileHelper.GetExtension(name),
                    Path = FILE_PATH + pathload + name,
                    IsFolder = false
                };

                return Json(new AjaxResult(true, "上传成功!", result));
            }
            catch (Exception ex)
            {
                return Json(new AjaxResult(false, "上传失败:" + ex.Message));
            }
        }
    }
}